/*
* CourseServiceImpl.java
* Created on  2014-4-19 下午5:02
* 版本       修改时间          作者      修改内容
* V1.0.1    2014-4-19       gaoxinyu    初始版本
*
*/
package com.genghis.ptas.course.service.impl;

import com.genghis.core.page.entity.Page;
import com.genghis.core.page.entity.PageParameter;
import com.genghis.ptas.classify.service.ClassifyService;
import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.course.dao.CourseDao;
import com.genghis.ptas.course.entity.ChapterInfo;
import com.genghis.ptas.course.entity.CourseComment;
import com.genghis.ptas.course.entity.CourseInfo;
import com.genghis.ptas.course.entity.CourseRegister;
import com.genghis.ptas.course.service.CourseService;
import com.genghis.ptas.course.service.CourseStatisticsService;
import com.genghis.ptas.security.entity.User;
import com.genghis.ptas.security.entity.UserBaseInfo;
import com.genghis.ptas.security.service.UserService;
import com.genghis.ptas.statistic.entity.CourseStatistics;
import com.genghis.ptas.system.service.DictService;
import com.genghis.ptas.util.AddTotalTime;
import com.genghis.ptas.util.DateUtil;
import com.genghis.ptas.util.FileUp;
import com.genghis.ptas.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.util.List;

/**
 * 类的描述信息
 *
 * @author fengxuanzhen
 * @version 1.0.1
 */
@Service("courseService")
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private UserService userService;

    @Autowired
    private ClassifyService classifyService;

    @Autowired
    private DictService dictService;

    @Autowired
    private CourseStatisticsService courseStatisticsService;

    @Override
    public Page<CourseInfo> findCoursePageList(PageParameter pageParameter, CourseInfo courseInfo) {
        Page<CourseInfo> coursePage = courseDao.findCoursePageList(pageParameter, courseInfo);
        for (CourseInfo course : coursePage.getResultList()) {
            course.setShowCourseType(classifyService.findTypeValuesById(course.getCourseType()).getTypeValue());
            course.setShowState(dictService.changeDictCodeToValue(course.getState(), DictConstant.AUDIT_STATE));
        }
        return coursePage;
    }

    @Override
    public List<CourseInfo> findCourseList() {
        String userName = LoginUserUtil.findLoginUserName();
        int userId = null == userName ? DictConstant.MINUS_ONE : userService.findFullUserByUserLoginName(userName).getId();
        List<CourseInfo> coursePage = courseDao.findCourseList(userId);
        for (CourseInfo course : coursePage) {
            course.setIsRegister(null != course.getShowRegister() && !"".equals(course.getShowRegister()));
            course.setShowCourseType(classifyService.findTypeValuesById(course.getCourseType()).getTypeValue());
        }
        return coursePage;
    }

    @Override
    public int addCourse(CourseInfo courseInfo) {
        return courseDao.addCourse(courseInfo);
    }

    @Override
    public void editCourse(CourseInfo courseInfo) {
        courseInfo.setUpDate(DateUtil.getSystemDate(DictConstant.DATE_FORMAT));
        courseDao.editCourse(courseInfo);
    }

    @Override
    public List<ChapterInfo> findChapterByCourseId(Integer id) {
        return courseDao.findChapterByCourseId(id);
    }

    @Override
    public CourseInfo findCourseByCourseId(Integer id) {
        CourseInfo courseInfo = courseDao.findCourseByCourseId(id);
        courseInfo.setShowCourseType(classifyService.findTypeValuesById(courseInfo.getCourseType()).getTypeValue());
        courseInfo.setShowQuality(dictService.changeDictCodeToValue(courseInfo.getQuality(), DictConstant.QUALITY));
        return courseInfo;
    }

    @Override
    public void deleteCourseInfoById(Integer id) {
        courseDao.deleteCourseInfoById(id);
    }

    @Override
    public void changeAuditState(String ids, int auditState) {
        CourseInfo auditInfo = new CourseInfo();
        auditInfo.setState(auditState);
        String allId[] = ids.split(",");
        for (String id : allId) {
            auditInfo.setId(Integer.parseInt(id));
            courseDao.changeAuditState(auditInfo);
        }
    }

    @Override
    public Boolean checkAuditInfoAuditState(String ids, int state) {
        String allId[] = ids.split(",");
        for (String id : allId) {
            if (courseDao.findCourseByCourseId(Integer.parseInt(id)).getState() != state) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void addCourseComment(CourseComment courseComment) {
        int userId = userService.findUserByLoginName(LoginUserUtil.findLoginUserName()).getId();
        courseComment.setUserId(userId);
        courseComment.setCommentDate(DateUtil.getSystemDate("yyyy-MM-dd HH:mm:ss"));
        courseDao.addCourseComment(courseComment);
    }

    @Override
    public List<CourseComment> findCourseCommentByCourseId(Integer id) {
        User user = new User(44);
        if (LoginUserUtil.findLoginUserName() != null) {
            user = userService.findUserByLoginName(LoginUserUtil.findLoginUserName());
        }
        List<CourseComment> courseCommentList = courseDao.findCourseCommentByCourseId(id);
        for (CourseComment courseComment : courseCommentList) {
            User userTemp = userService.findUserAllInfoById(courseComment.getUserId());
            if (null != userTemp) {
                UserBaseInfo userBaseInfo = userService.findUserBaseInfoByUserId(courseComment.getUserId());
                courseComment.setUserPhotoUrl(userBaseInfo.getPhotoUrl());
                courseComment.setUserName(userTemp.getUserName());
                if (courseComment.getUserId() == user.getId()) {
                    courseComment.setJudgeUser(1);
                } else {
                    courseComment.setJudgeUser(0);
                }
            }

        }
        return courseCommentList;
    }

    @Override
    public List<CourseInfo> findCourseListByTypeIdAndName(Integer typeId, String searchName) {
        return courseDao.findCourseListByTypeIdAndName(typeId, searchName);
    }

    @Override
    public List<CourseInfo> findCourseListByCourseName(String courseName) {
        return courseDao.findCourseListByCourseName(courseName);
    }

    @Override
    public List<CourseInfo> findUploadCourseListByUserId(Integer userId) {
        return courseDao.findUploadCourseListByUserId(userId);
    }

    @Override
    public List<CourseInfo> findTopCollectCourse(int userId) {
        return courseDao.findTopCollectCourse(userId);
    }

    @Override
    public List<CourseInfo> findTopRegisterCourse(int userId) {
        return courseDao.findTopRegisterCourse(userId);
    }

    @Override
    public int findRegisterThisMonth(User user) {
        return courseDao.findRegisterThisMonth(user).size();
    }

    @Override
    public String sumStudyTimeThisMonth(User user) {
        List<CourseRegister> courseRegisters = courseDao.findRegisterThisMonth(user);
        return AddTotalTime.getTotalTime(courseRegisters);
    }

    @Override
    public Boolean upload(HttpServletRequest request, CourseInfo courseInfo, String upFile, String upImg) throws ServletException, IOException, ParserConfigurationException, SAXException,
            XPathExpressionException {
        try {
            //上传Scorm课件和图片，返回使用的图片路径和文件绝对路径
            FileUp fileUp = new FileUp();
            String fileName = LoginUserUtil.findLoginUserName() + DateUtil.getSystemDate("yyyyMMddhhmmss");
            //0 图片路径 1 xml的文件夹路径
            String path[] = fileUp.upScorm(request, fileName, upFile, upImg);
            //解析章节到数据库
            List<ChapterInfo> scormNodes = fileUp.analyzeXml(path[1] + DictConstant.IMSMANIFEST);
            //将课件信息存入数据库
            courseInfo.setState(0);
            courseInfo.setUpDate(DateUtil.getSystemDate("yyyy-MM-dd HH:mm:ss"));
            courseInfo.setPhotoUrl(path[0].substring(path[0].indexOf(DictConstant.TOP_SCORM_FILE_NAME)));
            courseInfo.setUpUserId(userService.findUserByLoginName(LoginUserUtil.findLoginUserName()).getId());
            int id = courseDao.addCourse(courseInfo);
            //将统计信息存入库
            courseStatisticsService.addCourseStatistics(new CourseStatistics(0.0, "0", 0, 0, 0, id, ""));
            int all = 0;
            for (ChapterInfo chapterInfo : scormNodes) {
                if (chapterInfo.getChapterType().equals(DictConstant.ORGANIZATION)) {
                    all++;
                }
                chapterInfo.setCourseId(id);
                courseDao.addChapter(chapterInfo);
            }
            courseInfo.setChapterNum(all);
            courseInfo.setId(id);
            courseDao.editCourse(courseInfo);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
